#include "pickpoint.h"
#include <QApplication>
#include <QPainter>
#include <QPen>
#include <QMouseEvent>
#define diameter 80

PickPoint::PickPoint(QScreen *screen, QPoint optionPoint, WId windowId, int index, QDialog *parent): QDialog{parent}
{
    this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint);
    this->setMouseTracking(true);
    this->screen = screen;
    this->windowId = windowId;
    this->optionPoint = optionPoint;
    this->index = index;

    if (optionPoint == QPoint())
    {
        isSelected = false;
    }
    fullScreenButton = new QPushButton("确认");
    fullScreenButton->setStyleSheet(
        "QPushButton {"
        "  border: 2px solid #8FBC8F;"
        "  border-radius: 10px;"
        "  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E0FFFF, stop: 1 #8FBC8F);"
        "  color: #000000;"
        "  padding: 5px;"
        "  font-size:24px;"
        "  letter-spacing:3px; font-weight: 900; "
        "}"
        "QPushButton:hover {"
        "  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #C0FF3E, stop: 1 #87CEEB);"
        "}"
        "QPushButton:pressed {"
        "  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #7FFFD4, stop: 1 #32CD32);"
        "}"
        );
    fullScreenButton->setGeometry(screen->size().width()/2 -50, 40, 100, 40);
    fullScreenButton->setParent(this);
    connect(fullScreenButton, &QPushButton::clicked, this, &PickPoint::conformPoint);
}

void PickPoint::showEvent(QShowEvent *event)
{
    fullScreenBack = screen->grabWindow(windowId, 0, 0, screen->size().width(), screen->size().height());
    QPixmap mask(screen->size().width(), screen->size().height());
    mask.fill(QColor(255, 255, 0, 80));
    fullScreenDisplay = fullScreenBack;
    QPainter painter(&fullScreenDisplay);
    painter.drawPixmap(0, 0, mask);
}

void PickPoint::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    QPen pen;
    pen.setWidth(1);
    pen.setColor(Qt::red);
    pen.setStyle(Qt::SolidLine);
    p.setPen(pen);
    p.drawPixmap(0, 0, fullScreenDisplay);

    p.drawLine(mousePoint.x()-50, mousePoint.y(), mousePoint.x()+50, mousePoint.y());
    p.drawLine(mousePoint.x(), mousePoint.y()-50, mousePoint.x(), mousePoint.y()+50);
    QRect rect(mousePoint.x()-diameter/2, mousePoint.y()-diameter/2, diameter, diameter);
    p.drawEllipse(rect);

    if (isSelected)
    {
        p.drawEllipse(optionPoint.x()-2, optionPoint.y()-2, 4, 4);
    }
}

void PickPoint::mousePressEvent(QMouseEvent *event)
{
    isSelected = true;
    optionPoint = event->pos();
    this->update();
}

void PickPoint::mouseMoveEvent(QMouseEvent *event)
{
    mousePoint = event->pos();
    this->update();
}

void PickPoint::conformPoint()
{
    emit pointConfirmed(optionPoint, this->index);
    this->hide();
}
